use crate::core::message::{AppEvent, create_event_channel};
use crate::core::state::AppState;
use crate::ui::app::{AppData, DialogOption};
use crate::ui::handlers::*;
use crate::ui::renderer::render_ui;
use anyhow::Result;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use log::info;
use ratatui::{Terminal, backend::CrosstermBackend};
use std::io;
use tokio::select;

pub async fn run() -> Result<()> {
    // 初始化终端
    let stdout = io::stdout();
    enable_raw_mode()?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    crossterm::execute!(
        io::stdout(),
        crossterm::terminal::EnterAlternateScreen,
        crossterm::event::EnableMouseCapture
    )?;

    // 创建全局事件通道
    let (event_tx, mut event_rx) = create_event_channel(100);

    // 初始化应用状态
    let app_data = AppData::new();
    let app_state = AppState::new(app_data, event_tx.clone());

    // 启动后台任务
    let input_handler = tokio::spawn(handle_input(event_tx.clone()));

    // 启动通知检查任务
    let notification_checker =
        tokio::spawn(handle_notifications(event_tx.clone(), app_state.clone()));

    // 检查是否在Git仓库中
    app_state.git_manager.check_repository().await?;
    app_state.git_manager.get_repo_status().await?;

    // 清屏并初始渲染
    terminal.clear()?;
    {
        let app = app_state.app_data.lock().await;
        render_ui(&mut terminal, &app)?;
    }

    // 主事件循环
    'main: loop {
        select! {
            Some(event) = event_rx.recv() => {
                match event {
                    AppEvent::Quit => {
                        info!("Exiting application...");
                        break 'main
                    },

                    AppEvent::Render => {
                        let app = app_state.app_data.lock().await;
                        render_ui(&mut terminal, &app)?;
                    },

                    AppEvent::GitOperationStart { operation } => {
                        info!("Starting Git operation: {}", operation);
                        app_state.update_app(|app| {
                            app.set_notification(format!("Starting {}", operation), 3000);
                        }).await;
                    },

                    AppEvent::GitOperationComplete { operation, result } => {
                        info!("Git operation completed: {}", operation);
                        process_git_result(&app_state, &operation, result).await?;
                    },

                    AppEvent::GitOperationError { operation, error } => {
                        info!("Git operation error: {}", error);
                        app_state.update_app(|app| {
                            app.set_notification(format!("Error in {}: {}", operation, error), 5000);
                        }).await;
                    },
                    AppEvent::KeyPress(key_event) => {
                        info!("Key pressed: {:?}", key_event.code);
                        // 根据当前UI状态处理按键
                        let ui_state = {
                            let app = app_state.app_data.lock().await;
                            app.ui_state.clone()
                        };
                        match ui_state {
                            crate::ui::app::AppState::BranchList => {
                                // 处理分支列表中的按键
                                handle_branch_key(&app_state, key_event.code).await?;
                            },
                            crate::ui::app::AppState::CommitList => {
                                // 提交列表状态下的按键处理...
                                handle_commit_key(&app_state, key_event.code).await?;
                            },
                            crate::ui::app::AppState::MergeList => {
                                // 合并列表状态下的按键处理...
                                handle_merge_key(&app_state, key_event.code).await?;
                            },
                            crate::ui::app::AppState::Dialog => {
                                // 对话框状态下的按键处理...
                                handle_dialog_key(&app_state, key_event.code).await?;
                            },
                            // 处理其他UI状态...
                        }
                    },

                    AppEvent::BranchSelected(branch_name) => {
                        info!("Branch selected: {}", branch_name);
                        // 异步加载分支提交历史
                        app_state.git_manager.check_branch_status(&branch_name).await?;
                    },
                    AppEvent::ShowBranchSwitchDialog { branch, has_changes } => {
                        info!("Showing branch switch dialog for branch: {}", branch);
                        // 创建对话框选项
                        let mut dialog_options = vec![
                            DialogOption {
                                label: "Switch branch".to_string(),
                                value: format!("checkout:{}", branch),
                            }
                        ];

                        // 如果有未提交的修改，添加更多选项
                        if has_changes {
                            dialog_options.push(DialogOption {
                                label: "Force switch (discard changes)".to_string(),
                                value: format!("checkout_force:{}", branch),
                            });

                            dialog_options.push(DialogOption {
                                label: "Stash changes and switch".to_string(),
                                value: format!("stash_checkout:{}", branch),
                            });
                        }

                        // 显示确认对话框
                        app_state.update_app(|app| {
                            app.show_dialog(
                                "Switch Branch".to_string(),
                                format!("Do you want to switch to branch '{}'?", branch),
                                dialog_options,
                            );
                        }).await;
                    },

                    AppEvent::ShowMergeList(branch) => {
                        // 首先获取当前分支
                        if let Ok(current_branch) = crate::git::commands::get_current_branch().await {
                            // 设置合并源分支和更新UI状态
                            app_state
                                .update_app(|app| {
                                    app.merge_source_branch = Some(branch.clone());
                                    app.ui_state = crate::ui::app::AppState::MergeList;
                                    app.selected_index = 0;
                                    app.set_notification(
                                        format!(
                                            "Loading diff commits between '{}' and '{}'",
                                            branch, current_branch
                                        ),
                                        1500,
                                    );
                                    // 清空之前的提交列表，以便用户知道正在加载
                                    app.commits.clear();
                                    app.clear_commit_selections();
                                })
                                .await;

                            // 获取分支差异提交（源分支有但目标分支没有的提交）
                            app_state
                                .git_manager
                                .get_branch_diff_commits(&branch, &current_branch)
                                .await?;
                        }
                    }

                    AppEvent::MergeSelected { branch, commit_ids } => {
                        if commit_ids.is_empty() {
                            continue;
                        }

                        // 执行合并操作
                        let merge_op = app_state.git_manager.merge_commits(&branch, commit_ids.clone());

                        // 等待合并操作完成
                        if let Ok(_) = merge_op.wait().await {
                            app_state.update_app(|app| {
                                app.set_notification(
                                    format!("Successfully merged {} commit(s) from '{}'", commit_ids.len(), branch),
                                    3000,
                                );
                            }).await;

                            // 更新仓库状态
                            app_state.git_manager.get_repo_status().await?;

                            // 如果用户仍在合并列表视图中，则刷新列表以更新显示
                            let (should_refresh, merge_source_branch, current_branch) = {
                                let app = app_state.app_data.lock().await;
                                (
                                    app.ui_state == crate::ui::app::AppState::MergeList,
                                    app.merge_source_branch.clone(),
                                    app.current_branch.clone()
                                )
                            };

                            if should_refresh && merge_source_branch.is_some() && current_branch.is_some() {
                                // 重新加载未合并的提交
                                app_state
                                    .git_manager
                                    .get_branch_diff_commits(
                                        &merge_source_branch.unwrap(),
                                        &current_branch.unwrap()
                                    )
                                    .await?;
                            }
                        }
                    }
                    AppEvent::MergeCancelled => {
                        // 如果需要特殊处理可以在此处理
                    }

                    AppEvent::LoadCommitDiff(commit_id) => {
                        info!("Loading diff for commit: {}", commit_id);
                        // 设置加载状态
                        app_state.update_app(|app| {
                            app.current_diff = Some("Loading diff...".to_string());
                        }).await;

                        let tx_clone = event_tx.clone();
                        tokio::spawn(async move {
                            match crate::git::commands::commit::get_commit_diff(&commit_id).await {
                                Ok(diff_str) => {
                                    let _ = tx_clone.send(AppEvent::CommitDiffLoaded(Ok(diff_str))).await;
                                }
                                Err(e) => {
                                    let _ = tx_clone.send(AppEvent::CommitDiffLoaded(Err(e.to_string()))).await;
                                }
                            }
                        });
                    }

                    AppEvent::CommitDiffLoaded(result) => {
                        match result {
                            Ok(diff_str) => {
                                app_state.update_app(|app| {
                                    app.current_diff = Some(diff_str);
                                }).await;
                            }
                            Err(err_msg) => {
                                app_state.update_app(|app| {
                                    app.current_diff = Some(format!("Error loading diff: {}", err_msg));
                                    app.set_notification(format!("Failed to load diff: {}", err_msg), 3000);
                                }).await;
                            }
                        }
                        // update_app already sends Render event
                    }

                    // 处理其他事件...
                    _ => {}
                }
            }
        }
    }

    // 清理并退出
    input_handler.abort();
    notification_checker.abort();

    crossterm::execute!(
        terminal.backend_mut(),
        crossterm::terminal::LeaveAlternateScreen,
        crossterm::event::DisableMouseCapture
    )?;
    disable_raw_mode()?;
    terminal.show_cursor()?;

    Ok(())
}
